package com.shjn.squirrel.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.BootUpReq;
import com.shjn.squirrel.bean.httpBean.DeviceIdReq;
import com.shjn.squirrel.bean.httpBean.FactorySettingReq;
import com.shjn.squirrel.bean.httpBean.RespCommonResult;
import com.shjn.squirrel.bean.storageBean.WastePrice;
import com.shjn.squirrel.bean.storageBean.WorkSetting;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.utils.OkhttpHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 程序初始化数据显示页（出厂设置、开机启动、获取垃圾价格）
 */
public class InitPageFragment extends BaseFragment {

    private static InitPageFragment instance;

    public InitPageFragment() {
    }

    public synchronized static InitPageFragment getInstance() {
        if (instance == null) {
            instance = new InitPageFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.init_page, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        init();
        //----------测试用-------------//
        //更新客服电话设备ID
        final String deviceID = "201900032";
        final String serviceTel = "021-12345678";
        //设置Top页设备ID显示客服电话
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TopFragment.getInstance().setDeviceID(deviceID);
                TopFragment.getInstance().setServiceTel(serviceTel);
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mActivity.getFragmentManager().beginTransaction()
                        .remove(BackgroundFragment.getInstance())
                        .remove(TopFragment.getInstance())
                        .remove(InitPageFragment.getInstance())
                        .remove(BottomFragment.getInstance())
                        .replace(R.id.boot, AdvFragment.getInstance())
                        .commit();
            }
        }).start();
    }

    /**
     * 初始化
     */
    private void init() {
        //对主板进行时间校准
        setSer();
        //判断有无出厂设置(Constant.baseUrl +"machine/setting/factoryMode")
        if (LocalStorage.getDeviceID(MyApplication.getInstance()).isEmpty()) {
            OkhttpHelper.postRequest(Constant.myBaseUrl + "squirrelWebDemo/factorySettingServlet",
                    new Gson().toJson(new FactorySettingReq("898600562209A0715741", LocalStorage.getLocation(MyApplication.getInstance()).getLongitude(), LocalStorage.getLocation(MyApplication.getInstance()).getLatitude())),
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.i("info", "factoryMode_onFailure: " + e.getMessage());
                            OkhttpHelper.requestAgain(call, this);
                        }

                        @Override
                        public void onResponse(Call call, Response response) {
                            try {
                                RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
                                if (result.getStateCode() == 1) {
                                    if (result.getResult().get("deviceID") != null) {
                                        final String deviceID = (String) result.getResult().get("deviceID");
//                                        //所有称重板1清零
//                                        mActivity.serialPortUtils.sendSerialPort("androidP601:1;");   供手机测试，临时取消
//                                        //所有称重板1校准
//                                        mActivity.serialPortUtils.sendSerialPort("androidP602:1;");
//                                        //所有称重板2清零
//                                        mActivity.serialPortUtils.sendSerialPort("androidP611:1;");
//                                        //所有称重板2校准
//                                        mActivity.serialPortUtils.sendSerialPort("androidP612:1;");
                                        //保存设备ID
                                        LocalStorage.saveDeviceID(MyApplication.getInstance(), deviceID);
                                        //设置Top页设备ID显示
                                        mActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                TopFragment.getInstance().setDeviceID(deviceID);
                                            }
                                        });
                                    }
                                    //开机启动
                                    bootInit();
                                }
                            } catch (IOException e) {
                                Log.i("info", "factoryMode_onFailure: " + e.getMessage());
                                OkhttpHelper.requestAgain(call, this);
                            }
                        }
                    });
        } else {
            //开机启动
            bootInit();
        }

    }

    /**
     * 对主板进行时间校准
     */
    private void setSer() {
        Calendar calendar = Calendar.getInstance();
        long lTime = calendar.getTimeInMillis();
        calendar.setTimeInMillis(lTime);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String date = format.format(new Date());
//        mActivity.serialPortUtils.sendSerialPort("androidC3:" + date + "-" + week); 供手机测试，临时取消
    }

    /**
     * 开机启动，数据初始化
     */
    private void bootInit() {
        //1.开机启动(Constant.baseUrl +"machine/setting/bootUp")
        OkhttpHelper.postRequest(Constant.myBaseUrl + "squirrelWebDemo/bootUpServlet",
                new Gson().toJson(new BootUpReq(LocalStorage.getDeviceID(MyApplication.getInstance()), "898600562209A0715741",
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
                        LocalStorage.getLocation(MyApplication.getInstance()).getLongitude(),
                        LocalStorage.getLocation(MyApplication.getInstance()).getLatitude())),
                new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("info", "bootUp_onFailure: " + e.getMessage());
                        OkhttpHelper.requestAgain(call, this);
                    }

                    @Override
                    public void onResponse(Call call, Response response) {
                        try {
                            //2.获取回收机相关信息
                            RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
                            if (result.getStateCode() == 1) {
                                WorkSetting workSetting = LocalStorage.getWorkSetting(MyApplication.getInstance());
                                if (result.getResult().get("serviceTel") != null) {
                                    final String serviceTel = (String) result.getResult().get("serviceTel");
                                    workSetting.setServiceTel(serviceTel);
                                    //更新客服电话
                                    mActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            TopFragment.getInstance().setServiceTel(serviceTel);
                                        }
                                    });
                                }
                                if (result.getResult().get("openDutyCycle") != null) {
                                    int openDutyCycle = (int) ((double) result.getResult().get("openDutyCycle"));
                                    workSetting.setOpenDutyCycle(openDutyCycle);
                                    //分桶设置-投口电机开门占空比
//                                    mActivity.serialPortUtils.sendSerialPort("androidP139:" + "0-" + openDutyCycle + ",1-" + openDutyCycle + ",2-" + openDutyCycle
//                                            + ",3-" + openDutyCycle + ",4-" + openDutyCycle + ",5-" + openDutyCycle + ",6-" + openDutyCycle + ";");
                                }
                                if (result.getResult().get("openCurrentLimit") != null) {
                                    int openCurrentLimit = (int) ((double) result.getResult().get("openCurrentLimit"));
                                    workSetting.setOpenCurrentLimit(openCurrentLimit);
                                    //分桶设置-投口电机开门电流限值
//                                    mActivity.serialPortUtils.sendSerialPort("androidP140:" + "0-" + openCurrentLimit + ",1-" + openCurrentLimit + ",2-" + openCurrentLimit
//                                            + ",3-" + openCurrentLimit + ",4-" + openCurrentLimit + ",5-" + openCurrentLimit + ",6-" + openCurrentLimit + ";");
                                }
                                if (result.getResult().get("closeDutyCycle") != null) {
                                    int closeDutyCycle = (int) ((double) result.getResult().get("closeDutyCycle"));
                                    workSetting.setCloseDutyCycle(closeDutyCycle);
                                    //分桶设置-投口电机关门占空比
//                                    mActivity.serialPortUtils.sendSerialPort("androidP141:" + "0-" + closeDutyCycle + ",1-" + closeDutyCycle + ",2-" + closeDutyCycle
//                                            + ",3-" + closeDutyCycle + ",4-" + closeDutyCycle + ",5-" + closeDutyCycle + ",6-" + closeDutyCycle + ";");
                                }
                                if (result.getResult().get("closeCurrentLimit") != null) {
                                    int closeCurrentLimit = (int) ((double) result.getResult().get("closeCurrentLimit"));
                                    workSetting.setCloseCurrentLimit(closeCurrentLimit);
                                    //分桶设置-投口电机关门电流限值
//                                    mActivity.serialPortUtils.sendSerialPort("androidP142:" + "0-" + closeCurrentLimit + ",1-" + closeCurrentLimit + ",2-" + closeCurrentLimit
//                                            + ",3-" + closeCurrentLimit + ",4-" + closeCurrentLimit + ",5-" + closeCurrentLimit + ",6-" + closeCurrentLimit + ";");
                                }
                                if (result.getResult().get("holdTime") != null) {
                                    int holdTime = (int) ((double) result.getResult().get("holdTime"));
                                    workSetting.setHoldTime(holdTime);
                                    //分桶设置-投口开门保持时间
//                                    mActivity.serialPortUtils.sendSerialPort("androidP143:" + "0-" + holdTime + ",1-" + holdTime + ",2-" + holdTime
//                                            + ",3-" + holdTime + ",4-" + holdTime + ",5-" + holdTime + ",6-" + holdTime + ";");
                                }
                                if (result.getResult().get("handshakeCycle") != null) {
                                    int handshakeCycle = (int) ((double) result.getResult().get("handshakeCycle"));
                                    workSetting.setHandshakeCycle(handshakeCycle);
                                    //系统数值设置-握手周期
//                                    mActivity.serialPortUtils.sendSerialPort("androidP201:" + handshakeCycle + ";");
                                }
                                if (result.getResult().get("detectionCycle") != null) {
                                    int detectionCycle = (int) ((double) result.getResult().get("detectionCycle"));
                                    workSetting.setDetectionCycle(detectionCycle);
                                    //系统数值设置-检测周期
//                                    mActivity.serialPortUtils.sendSerialPort("androidP206:" + detectionCycle + ";");
                                }
                                if (result.getResult().get("rightWeightClear") != null) {
                                    int rightWeightClear = (int) ((double) result.getResult().get("rightWeightClear"));
                                    workSetting.setRightWeightClear(rightWeightClear);
                                    //所有称重板1清零
//                                    mActivity.serialPortUtils.sendSerialPort("androidP601:" + rightWeightClear + ";");
                                }
                                if (result.getResult().get("rightWeightAdjust") != null) {
                                    int rightWeightAdjust = (int) ((double) result.getResult().get("rightWeightAdjust"));
                                    workSetting.setRightWeightAdjust(rightWeightAdjust);
                                    //所有称重板1校准
//                                    mActivity.serialPortUtils.sendSerialPort("androidP602:" + rightWeightAdjust + ";");
                                }
                                if (result.getResult().get("leftWeightClear") != null) {
                                    int leftWeightClear = (int) ((double) result.getResult().get("leftWeightClear"));
                                    workSetting.setLeftWeightClear(leftWeightClear);
                                    //所有称重板2清零
//                                    mActivity.serialPortUtils.sendSerialPort("androidP611:" + leftWeightClear + ";");
                                }
                                if (result.getResult().get("leftWeightAdjust") != null) {
                                    int leftWeightAdjust = (int) ((double) result.getResult().get("leftWeightAdjust"));
                                    workSetting.setLeftWeightAdjust(leftWeightAdjust);
                                    //所有称重板2校准
//                                    mActivity.serialPortUtils.sendSerialPort("androidP612:" + leftWeightAdjust + ";");
                                }
                                //保存工作状态
                                LocalStorage.saveWorkSetting(MyApplication.getInstance(), workSetting);
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                //----------测试用-------------//
                                mActivity.getFragmentManager().beginTransaction()
                                        .remove(BackgroundFragment.getInstance())
                                        .remove(TopFragment.getInstance())
                                        .remove(InitPageFragment.getInstance())
                                        .remove(BottomFragment.getInstance())
                                        .replace(R.id.boot, AdvFragment.getInstance())
                                        .commit();
                                //----------测试用-------------//

                                //3.获取垃圾价格
//                                OkhttpHelper.postRequest(Constant.baseUrl + "machine/home/price",
//                                        new Gson().toJson(new DeviceIdReq(LocalStorage.getDeviceID(MyApplication.getInstance()))),
//                                        new Callback() {
//                                            @Override
//                                            public void onFailure(Call call, IOException e) {
//                                                Log.i("info", "price_onFailure: " + e.getMessage());
//                                                OkhttpHelper.requestAgain(call, this);
//
//                                            }
//
//                                            @Override
//                                            public void onResponse(Call call, Response response) {
//                                                try {
//                                                    RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
//                                                    if (result.getStateCode() == 1) {
//
//                                                        //保存当前垃圾价格
//                                                        LocalStorage.saveWastePrice(MyApplication.getInstance(), (ArrayList<WastePrice>) result.getResult().get("wastePrice"));
//
//                                                        //4.跳转到待机页
//                                                        mActivity.getFragmentManager().beginTransaction()
//                                                                .remove(BackgroundFragment.getInstance())
//                                                                .remove(TopFragment.getInstance())
//                                                                .remove(InitPageFragment.getInstance())
//                                                                .remove(BottomFragment.getInstance())
//                                                                .replace(R.id.boot, AdvFragment.getInstance())
//                                                                .commit();
//                                                    }
//                                                } catch (IOException e) {
//                                                    Log.i("info", "price_onFailure: " + e.getMessage());
//                                                    OkhttpHelper.requestAgain(call, this);
//                                                }
//                                            }
//                                        });

                            }
                        } catch (IOException e) {
                            Log.i("info", "bootUp_onFailure: " + e.getMessage());
                            OkhttpHelper.requestAgain(call, this);
                        }

                    }
                });
    }

}
